package com.taskinception;

import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.taskinception.connectivity.DatabaseAdapter;
import com.taskinception.model.Task;
import com.taskinception.utils.Alert;
import com.taskinception.utils.TaskListAdapter;

/**
 * <p>
 * Startup activity. It displays either the details or a list of children for
 * the current {@link com.taskinception.model.Task Task}.
 * </p>
 *
 * <p>
 * Unless {@link com.taskinception.TaskActivity#TAG_CURRENT_TASK
 * TAG_CURRENT_TASK} is given in the firing {@link android.app.Intent Intent},
 * the current {@link com.taskinception.model.Task Task}{@code id} is 0 (Main
 * task list).
 * </p>
 *
 * @author Remy Parzinski
 *
 */
public class TaskActivity extends ListActivity {

    /**
     * Tag used for determining the current Task to display in the Activity. Use
     * this tag in the firing {@link android.app.Intent Intent} when navigating
     * to another {@link com.taskinception.model.Task Task}
     */
    public static final String TAG_CURRENT_TASK = "current_task";

    /**
     * Instance of the {@link com.taskinception.connectivity.DatabaseAdapter
     * DatabaseAdapter} class.
     *
     * @see DatabaseAdapter
     */
    private DatabaseAdapter mDbAdapter = null;

    /**
     * Instance of the main {@link android.view.Menu Menu} class. Is not
     * instantiated untill
     * {@link android.app.Activity#onCreateOptionsMenu(Menu)
     * onCreateOptionsMenu(Menu)} is called.
     */
    @SuppressWarnings("unused")
    private Menu mMenu = null;

    /**
     * Root element for the current {@linkplain com.taskinception.model.Task
     * Task} list
     */
    private Task mRootTask = null;

    /**
     * Unique ID of this device for
     * {@link com.taskinception.model.Task#setRemoteId(String)}
     */
    public static String android_id;

    /**
     * Build the action bar. Show the title and progress of the current
     * {@link com.taskinception.model.Task Task}. Also, build the crumble path,
     * if available
     */
    private void buildActionBar() {
        ActionBar actionBar = getActionBar();

        // Draw the title and subtitle, if mRootTask has children
        mRootTask.setChildren(mDbAdapter.fetchFromParentAsList(mRootTask));
        for (Task child : mRootTask.getChildren()) {
            child.setChildren(mDbAdapter.fetchFromParentAsList(child));
        }
        actionBar.setTitle(mRootTask.getTitle());
        if (mRootTask.isList()) {
            actionBar.setSubtitle(mRootTask.getProgress());
        }
//        if (mRootTask.getId() >= 0) {
//        } else {
//            // Remove the title to make way for the custom View, which shows the
//            // title
//            actionBar.setTitle(null);
//
//            // Build the magic bar
//            actionBar.setCustomView(R.layout.task_action_bar);
//            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
//                    | ActionBar.DISPLAY_SHOW_HOME);
//
//            // Set the title
//            ((TextView) actionBar.getCustomView().findViewById(R.id.task_title))
//                    .setText(mRootTask.getTitle());
//
//            if (mRootTask.isList()) {
//                // Set the progress
//                ((TextView) actionBar.getCustomView().findViewById(
//                        R.id.task_progress)).setText(mRootTask.getProgress());
//            } else {
//                // "Remove" the progress textfield
//                ((TextView) actionBar.getCustomView().findViewById(
//                        R.id.task_progress)).setVisibility(View.GONE);
//            }
//
//            LinearLayout base = (LinearLayout) actionBar.getCustomView()
//                    .findViewById(R.id.task_crumble_path);
//
//            Context ctx = actionBar.getThemedContext();
//
//            int position = 0;
//            List<Task> path = new ArrayList<Task>(position);
//
//            Task parent = mRootTask;
//            do {
//                parent = mDbAdapter.fetchTask(parent.getParent());
//                path.add(position++, parent);
//            } while (position < 3 && parent.getId() > 0);
//            Collections.reverse(path);
//
//            LayoutInflater inflater = LayoutInflater.from(ctx);
//
//            for (Task crumble : path) {
//                // Button b = new Button(ctx, null, R.layout.task_action_bar);
//                Button b = (Button) inflater.inflate(
//                        R.layout.task_action_bar_button, null);
//                // b.setLayoutParams(actionBarCrumblePathButtonLayout);
//                // b.setBackgroundResource(R.drawable.crumble_path_button);
//
//                // Let the Button's text be ellipsized when necessary. Prevents
//                // word wrapping, which may cause the buttons to use >= 2 lines
//                b.setSingleLine();
//                b.setText(crumble.getTitle());
//                b.setGravity(Gravity.CENTER);
//                b.setEllipsize(TextUtils.TruncateAt.END);
//
//                // Make the Task id available for the click handler
//                b.setTag(crumble.getId());
//
//                b.setOnClickListener(new OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        v = (Button) v;
//                        Long id = (Long) v.getTag();
//
//                        // Prevent the main list to be in the stack twice
//                        if (id == 0) {
//                            finish();
//                            return;
//                        }
//
//                        // Go "back" one step
//                        Intent intent = new Intent(TaskActivity.this,
//                                TaskActivity.class);
//                        intent.putExtra(TaskActivity.TAG_CURRENT_TASK, id);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                    }
//                });
//
//                base.addView(b);
//            }
//
//        }
    }

    /**
     * When there are tasks available, display them in a
     * {@link android.widget.ListView ListView}. Display the details otherwise.
     */
    public void displayTaskList() {
        TextView bodyText = (TextView) findViewById(R.id.task_body);
        ListView list = getListView();

        // Display the "list is empty" message, when there are no tasks
        mRootTask.setChildren(mDbAdapter.fetchFromParentAsList(mRootTask));
        if (!mRootTask.isList()) {
            if (mRootTask.getBody().isEmpty()) {
                bodyText.setText(R.string.list_empty);
            } else {
                bodyText.setText(mRootTask.getBody());
            }
            bodyText.setVisibility(View.VISIBLE);
            list.setVisibility(View.GONE);
            return;
        }
        bodyText.setVisibility(View.GONE);
        list.setVisibility(View.VISIBLE);

        list.setAdapter(new TaskListAdapter(TaskActivity.this,
                R.layout.task_list_row, mRootTask.getChildren()));
        TaskListItemTouchListener listener = new TaskListItemTouchListener(this);

        list.setOnItemClickListener(listener);
        list.setOnCreateContextMenuListener(this);
        list.setItemsCanFocus(true);

        registerForContextMenu(list);
    }

    public void onShareButtonClick(View view) {
        ((TaskListItemTouchListener) getListView().getOnItemClickListener())
                .onClick(view);
    }

    /**
     * Perform the initial setup.
     */
    private void init() {

        android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

        // Make sure the database is available
        mDbAdapter = new DatabaseAdapter(this).open();
        // TIApplication.getInstance().getDatabaseAdapter();

        TIApplication.setContext(getApplicationContext());

        // Obtain the data from the current task. If none is given in the Intent
        // extras, use the root Task instead (0)
        long currentTaskId = getIntent().getLongExtra(TAG_CURRENT_TASK, 0);
        if (currentTaskId > 0) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
        mRootTask = mDbAdapter.fetchTask(currentTaskId);
        mRootTask.dump();
        TIApplication.getInstance().setRootTask(mRootTask);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        build();
    }

    /**
     * Build the screen and all of its components.
     *
     * @see #init()
     * @see #buildActionBar()
     * @see #displayTaskList()
     */
    private void build() {
        init();
        buildActionBar();
        displayTaskList();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        // Some options are not available for the main task list
        if (mRootTask.getId() == 0) {
            menu.findItem(R.id.task_edit).setVisible(false);
            menu.findItem(R.id.task_share).setVisible(false);
            menu.findItem(R.id.task_move).setVisible(false);
        }

        // Only make available when necessary
        if (!mRootTask.hasFinishedChildren()) {
            menu.findItem(R.id.clear_finished).setEnabled(false);
        }

        // Make the Menu available for future reference
        mMenu = menu;
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        CharSequence title = ((TextView) info.targetView
                .findViewById(R.id.task_title)).getText();
        CheckBox checkBox = (CheckBox) info.targetView
                .findViewById(R.id.task_checked);

        menu.setHeaderTitle(title);

        // Basic options for every Task
        menu.add(Menu.NONE, R.id.task_edit, Menu.NONE, R.string.edit_task);
        menu.add(Menu.NONE, R.id.task_share, Menu.NONE, R.string.share_task);
        menu.add(Menu.NONE, R.id.task_move, Menu.NONE, R.string.move_task);
        menu.add(Menu.NONE, R.id.task_delete, Menu.NONE, R.string.delete_task)
                .setEnabled(checkBox.isChecked());
        return;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDbAdapter.close();
        mRootTask = null;
        mMenu = null;
        finalize();
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        Intent intent;
        long id;
        if (featureId == Window.FEATURE_CONTEXT_MENU) {
            id = (Long) ((AdapterContextMenuInfo) item.getMenuInfo()).targetView
                    .getTag(R.id.task_id);
        } else {
            id = mRootTask.getId();
        }
        switch (item.getItemId()) {
            case android.R.id.home:
                // Go up one level
                // finish();
                intent = new Intent(TaskActivity.this, TaskActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(TAG_CURRENT_TASK, 0L);
                startActivity(intent);
                return true;
            case R.id.create_task:
                // Create a new Task
                intent = new Intent(this, EditTaskActivity.class);
                intent.putExtra(EditTaskActivity.TAG_PARENT, mRootTask.getId());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                return true;
            case R.id.task_edit:
                // Edit an existing Task
                intent = new Intent(TaskActivity.this, EditTaskActivity.class);
                intent.putExtra(EditTaskActivity.TAG_ID, id);
                startActivity(intent);
                return true;
            case R.id.task_move:
                // TODO: Make the "Move to other list" option available
            case R.id.task_share:
                // TODO (ben): Make the "Share" option available
            case R.id.clear_finished:
                // TODO: Make the "Clear finished" option available
                Alert.message(
                        TaskActivity.this,
                        "Coming soon...",
                        "This action is not yet available. It will be implemented shortly.",
                        null);
                return false;
            case R.id.task_delete:
                deleteTask(TIApplication.getInstance().getTask(id));
                build();
                return true;
//            case R.id.wifi_direct_enable_accept:
//                Intent wiFiIntent = new Intent(this, WiFiDirectActivity.class);
//                wiFiIntent.putExtra(WiFiDirectActivity.TASK_ID, mRootTask.getId());
//                wiFiIntent.putExtra(WiFiDirectActivity.MODE, "listen");
//                startActivity(wiFiIntent);
//                return true;
            default:
                return super.onMenuItemSelected(featureId, item);
        }
    }

    private boolean deleteTask(Task task) {
        return mDbAdapter.deleteTask(task.getId());
    }

    @Override
    protected void onResume() {
        super.onResume();
        build();
    }

    protected void finalize() {
        mDbAdapter.close();
        mRootTask = null;
        mMenu = null;
    }

    /**
     * Listener for the {@link android.widget.ListView ListView} Items
     *
     * @author Remy Parzinski
     */
    public static class TaskListItemTouchListener implements
            OnItemClickListener, View.OnClickListener {

        private Context _context;

        public TaskListItemTouchListener(Context ctx) {
            _context = ctx;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            Intent intent = new Intent(_context, TaskActivity.class);
            intent.putExtra(TaskActivity.TAG_CURRENT_TASK,
                    (Long) view.getTag(R.id.task_id));
            _context.startActivity(intent);
        }

        @Override
        public void onClick(View v) {
            v = (ImageView) v;
            long id = (Long) ((LinearLayout) v.getParent())
                    .getTag(R.id.task_id);
            Intent intent = new Intent(_context, WiFiDirectActivity.class);
            intent.putExtra(WiFiDirectActivity.TASK_ID, id);
            intent.putExtra(WiFiDirectActivity.MODE, "share");
            _context.startActivity(intent);
        }

    }

}
